package com.ultra.template.parse;


import com.ultra.enums.ArgumentTypeEnum;
import com.ultra.exception.UnableResolveTypeException;
import com.ultra.exception.UnknownTypeException;
import com.ultra.template.content.Argument;
import com.ultra.template.content.Pairs;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;


/**
 * @author yinger
 * @description TODO
 * @date 2024/12/30
 **/
public final class BasicParser {
    public static boolean isWrapperClass(Type type) {
        if (type instanceof Class) {
            Class<?> clazz = (Class<?>) type;
            if (clazz.isPrimitive()) {
                return false;
            }
            String name = clazz.getName();
            List<String> list = Arrays.asList("java.lang.Boolean", "java.lang.Byte", "java.lang.Short", "java.lang.Integer", "java.lang.Long", "java.lang.Float", "java.lang.Double", "java.lang.Character", "java.lang.String");
            // 判断是否是基本类型的包装类
            for (String s : list) {
                if (name.equals(s)) {
                    return true;
                }
            }
        }
        return false;
    }


    public static void createLeafObject(Argument argument) {
        argument.setIThCollection(Parser.times[argument.getDepth()]++);
        Parser.flatteningMap.put(new Pairs(argument.getIThArgument(), argument.getDepth(), argument.getIThCollection()), argument);
        Type type = argument.getType();
        if (type instanceof Class<?> && ((Class<?>) type).isPrimitive()) {
            argument.setClassName(type.toString());
            argument.setArgumentType(ArgumentTypeEnum.PRIMITIVE);
        } else if (BasicParser.isWrapperClass(type)) {
            argument.setArgumentType(ArgumentTypeEnum.WRAPPER);
            argument.setClassName(type.toString().substring(6));
        } else {
            // 3. 自定义类
            // TODO 例如 String
            System.out.println("Customize 自定义类 ... ");
            // 反射获取value字段和id字段
        }
    }

    public static void _fromCollection(Argument argument) throws UnableResolveTypeException, UnknownTypeException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        argument.setArgumentType(ArgumentTypeEnum.COLLECTION);
        argument.setClassName(String.class.getName());
        if (argument.getChild() == null || argument.getChild().length == 0) {
            argument.setChild(new Argument[]{new Argument()});
        }
        argument.getChild()[0].setType(char.class);
        Parser.parserDispatcher(argument.getChild()[0]);
    }
}
